﻿using HY.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System;
using WebApi.Helpers;
using WebApi.Model;
using WebApi.ViewModel;
using System.Collections.Generic;
using System.Linq;
using SqlSugar;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class YPutOnRecordController : BaseController
    {
        public YPutOnRecordController(ILogger<YPutOnRecordController> logger) : base(logger)
        {
        }

        /// <summary>
        /// 获取运输备案信息分页列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("GetPageList")]
        public async Task<ReturnModel> GetPageList(QueryYPutOnRecordVM model)
        {
            try
            {
                Expression<Func<YPutOnRecord, bool>> filter = e => true;
                if (!string.IsNullOrEmpty(model.GNumber))
                    filter = filter.And(c => c.GNumber.Contains(model.GNumber));
                if (!string.IsNullOrEmpty(model.YNumber))
                    filter = filter.And(c => c.YNumber.Contains(model.YNumber));
                if (!string.IsNullOrEmpty(model.YCompany))
                    filter = filter.And(c => c.YCompany.Contains(model.YCompany));
                if (!string.IsNullOrEmpty(model.PlateList))
                    filter = filter.And(c => c.PlateList.Contains(model.PlateList));
                if (model.BeginTime != null)
                    filter = filter.And(c => model.BeginTime <= c.EndDate);
                if (model.EndTime != null)
                    filter = filter.And(c => model.EndTime >= c.EndDate);
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel { PageIndex = model.PageIndex, PageSize = model.PageSize };
                var data = await DbHelper.YPutOnRecord.GetPageListAsync(filter, pageModel);
                return new ReturnModel { Count = pageModel.TotalCount, Data = data };
            }
            catch (Exception ex)
            {
                LogToDB("Monitor", "查询", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(GetPageList)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(YPutOnRecordController)}/{nameof(GetPageList)}", ex);
            }
        }

        [HttpPost("Add")]
        public async Task<ReturnModel> Add(YPutOnRecord model)
        {
            model.CreatTime = DateTime.Now;
            return await Save(model, true);
        }

        [HttpPost("Update")]
        public async Task<ReturnModel> Update(YPutOnRecord model)
        {
            return await Save(model, false);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isInsert"></param>
        /// <returns></returns>
        private async Task<ReturnModel> Save(YPutOnRecord model, bool isInsert)
        {
            try
            {
                if (model.Enable.Value)
                {
                    GPutOnRecord gPutOnRecord = DbHelper.GPutOnRecord.GetFirst(it => it.GNumber == model.GNumber);
                    List<YPutOnRecord> list = DbHelper.Db.Queryable<YPutOnRecord>().Where(it => it.GNumber == model.GNumber && it.Id != model.Id).Select(it => new YPutOnRecord { PlateList = it.PlateList, TotalWeight = SqlFunc.IsNull(it.TotalWeight, 0), RemainingWeight = SqlFunc.IsNull(it.RemainingWeight, 0), Enable = it.Enable }).ToList();
                    //获取除该数据外其他启用状态的分配总额
                    int allocatedWeight = list.Where(it => it.Enable == true).Sum(it => it.TotalWeight);
                    //获取除该数据外其他未启用状态已使用的分配额
                    int usedWeight = list.Where(it => it.Enable == true).Sum(it => it.TotalWeight - it.RemainingWeight.Value);
                    if ((gPutOnRecord.TotalWeight - usedWeight) < (allocatedWeight + model.TotalWeight))
                        return logger.Code_202("分配的运输重量大于购买备案号剩余可分配重量");

                    model.PlateList = model.PlateList?.Replace('，', ',').Replace(" ", "");
                    //以下判断购买备案号下属的运输备案号内，是否已使用过当前输入的车牌
                    if (!string.IsNullOrWhiteSpace(model.PlateList))
                    {
                        string[] plateArray = list.Where(it => it.Enable == true).Select(it => it.PlateList).ToArray();
                        if (plateArray.Length > 0)
                        {
                            string plateString = "," + string.Join(",", plateArray) + ",";
                            string existPlate = string.Empty;
                            foreach (string plate in model.PlateList.Split(','))
                            {
                                if (plateString.Contains($",{plate},"))
                                    existPlate += plate + ",";
                            }
                            if (!string.IsNullOrWhiteSpace(existPlate))
                                return logger.Code_202($"{existPlate.Trim(',')}在其他运输备案号已存在");
                        }
                    }
                }

                if (DbHelper.YPutOnRecord.IsAny(c => c.Id != model.Id && c.YNumber == model.YNumber))
                    return logger.Code_202("运输备案号已存在");
                else if (isInsert)
                    await DbHelper.YPutOnRecord.InsertAsync(model);
                else
                    await DbHelper.GetDbConn().Updateable(model).IgnoreColumns(it => it.CreatTime).ExecuteCommandAsync();
                LogToDB("YPutOnRecord", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("YPutOnRecord", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(GetPageList)}-{ex.Message}");
                return logger.ErrorModel(nameof(YPutOnRecordController) + "-" + nameof(Save), ex);
            }
        }

        [HttpPost("Delete/{id}")]
        public async Task<ReturnModel> Delete(int id)
        {
            try
            {
                YPutOnRecord model = DbHelper.YPutOnRecord.GetById(id);
                await DbHelper.YPutOnRecord.DeleteAsync(it => it.Id == id);
                LogToDB("YPutOnRecord", "删除", $"参数：{id},删除数据：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("YPutOnRecord", "删除", $"参数：{id}", "异常", $"{nameof(Delete)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(ReportController)}/{nameof(Delete)}", ex);
            }
        }
    }
}
